package com.aso114.project.exam;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.EvenBaseBean;
import com.aso114.project.bean.MsgEvent;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.QuestionContextListBean;
import com.aso114.project.bean.questioncontentListBean;
import com.aso114.project.commonview.NoPreloadViewPager;
import com.aso114.project.mvp.activity.SatGuideActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.MySharedPreferences;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class QuestionTestActivity extends BaseSimpleActivity {
    public static final String IS_EXAM = "is_exam";
    public static NoPreloadViewPager viewPager;
    @BindView(R.id.question_back)
    ImageView back;
    @BindView(R.id.question_countdown)
    TextView timer;
    @BindView(R.id.question_timer)
    LinearLayout timerLayout;

    @BindView(R.id.question_submit)
    TextView submit;
    @BindView(R.id.settingtv)
    TextView setting;
    @BindView(R.id.main_bar)
    LinearLayout mainBar;
    boolean isExam;
    @BindView(R.id.stop)
    TextView stop;
    @BindView(R.id.collect)
    TextView collect;

    TextView first, second, three, four, five;
    public static QuestionBean qdata;
    @BindView(R.id.que_conect)
    TextView queConect;
    @BindView(R.id.que_num)
    TextView queNum;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.titletv)
    TextView titletv;
    @BindView(R.id.remove)
    TextView remove;
    @BindView(R.id.question_toolbar)
    RelativeLayout questionToolbar;
    @BindView(R.id.main_viewpager)
    NoPreloadViewPager mainViewpager;
    @BindView(R.id.view)
    View view;

    private DefineTimer countDownTimer;
    boolean isstart = false;
    QuestionsFragment qufg;
    Intent intent;
    Dialog dialog;
    public static QuestionTestActivity instance;
    public static ArrayList<QuestionBaseBean> baseBean;

    private int pagerPosition = 0;
    private int position = 0;
    // 是否解析可见
    private boolean isAnalysis;
    private boolean isAnalysisOpen;
    private boolean isHistory;
    String title_tv = "真题模考";
    int submitpaper_type = 1;// 1 表示正常进入  返回需要提交未完成试卷   2 表示查看试卷报告
    MyPagerAdapter pagerAdapter;

    @Override
    protected int getResouseId() {
        return R.layout.question_main;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, questionToolbar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        instance = this;
        isAnalysis = getIntent().getBooleanExtra("isAnalysis", false);
        isAnalysisOpen = getIntent().getBooleanExtra("isAnalysisOpen", false);
        isHistory = getIntent().getBooleanExtra("isHistory", false);
        position = getIntent().getIntExtra("position", 0);
        viewPager = (NoPreloadViewPager) findViewById(R.id.main_viewpager);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOnPageChangeListener(new MyPagerChangeListner());
        isExam = getIntent().getBooleanExtra(IS_EXAM, false);


        if (isExam) {
            startTimer();
        }
        if (Constant.title_tv.equals("1")) {
            titletv.setText("考点练习");
            stop.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("2")) {
            titletv.setText("章节练习");
            stop.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("3")) {
            titletv.setText("真题模考");
        }
        if (Constant.title_tv.equals("4")) {
            titletv.setText("巩固模考");
        }
        if (Constant.title_tv.equals("5")) {
            titletv.setText("考试成绩");
            stop.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("6")) {
            titletv.setText("练习历史");

        }
        if (Constant.title_tv.equals("7")) {
            titletv.setText("错题练习");
            stop.setVisibility(View.GONE);
            queConect.setText("单项选择题");
            remove.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("8")) {
            titletv.setText("收藏题");
            Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                    .getMinimumHeight());

            collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
            collect.setTextColor(getResources().getColor(R.color.aff6559));
            queConect.setText("单项选择题");
            stop.setVisibility(View.GONE);
            remove.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("9")) {
            titletv.setText("真题模考");
        }
        if (Constant.title_tv.equals("10")) {
            titletv.setText("收藏题");

            stop.setVisibility(View.GONE);
        }
        if (Constant.title_tv.equals("11")) {
            titletv.setText("练习历史");
        }

        if (!isExam) {//如果不是考试,就隐藏
            timerLayout.setVisibility(View.GONE);
//            submit.setVisibility(View.GONE);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(QuestionBean event) {
        Log.i("yxp", "------------------1");
        if (event != null) {
            baseBean = new ArrayList<>();
            qdata = event;

            for (int i = 0; i < event.getQuestionBaseList().size(); i++) {
                for (int j = 0; j < event.getQuestionBaseList().get(i).getQuestionList().size();
                     j++) {
                    QuestionBaseBean questionBaseBean = new QuestionBaseBean();

                    questionBaseBean.setQuestionBaseId(event.getQuestionBaseList().get(i)
                            .getQuestionBasicId());
                    questionBaseBean.setPaperId(event.getQuestionBaseList().get(i).getPaperId
                            ());
                    questionBaseBean.setQuantity(event.getQuestionBaseList().get(i)
                            .getQuantity());
                    questionBaseBean.setTitle(event.getQuestionBaseList().get(i).getTitle());
                    questionBaseBean.setDescription(event.getQuestionBaseList().get(i)
                            .getDescription());
                    questionBaseBean.setRealPaperId(event.getQuestionBaseList().get(i)
                            .getRealPaperId());
                    questionBaseBean.setRealBaseId(event.getQuestionBaseList().get(i)
                            .getRealBaseId());
                    questionBaseBean.setQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionId());
                    questionBaseBean.setCateId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getCateId());
                    questionBaseBean.setBaseId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getBaseId());
                    questionBaseBean.setUserId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserId());
                    questionBaseBean.setRealQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getRealQuestionId());
                    questionBaseBean.setOrderNumber(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getOrderNumber());
                    questionBaseBean.setRealPaperTitle(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getRealPaperTitle());
                    questionBaseBean.setFormatContent(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getFormatContent());
                    questionBaseBean.setFormatImages(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getFormatImages());
                    questionBaseBean.setExamPaperType(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getExamPaperType());
                    questionBaseBean.setQuestionScore(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionScore());
                    questionBaseBean.setErrorScore(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getErrorScore());
                    questionBaseBean.setErrorScoreType(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getErrorScoreType());
                    questionBaseBean.setDeductionScore(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getDeductionScore());
                    questionBaseBean.setDifficultyFactor(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getDifficultyFactor());
                    questionBaseBean.setContextQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getContextQuestionId());
                    questionBaseBean.setAnswerCount(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getAnswerCount());
                    questionBaseBean.setAnswerErrorCount(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getAnswerErrorCount());
                    questionBaseBean.setQuestionTypeId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionTypeId());
                    questionBaseBean.setSpecialId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getSpecialId());
                    questionBaseBean.setCollect("1".equals(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getIsCollect()));

                    QuestionBaseBean.questionStatisticsInfo questionStatisticsInfo = new
                            QuestionBaseBean.questionStatisticsInfo();
                    questionStatisticsInfo.setQuestionStatisticId(event.getQuestionBaseList()
                            .get
                                    (i).getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getQuestionStatisticId());
                    questionStatisticsInfo.setQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getQuestionId());
                    questionStatisticsInfo.setRightRatio(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getRightRatio());
                    questionStatisticsInfo.setRightCount(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getRightCount());
                    questionStatisticsInfo.setWrongRatio(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getWrongRatio());
                    questionStatisticsInfo.setWrongCount(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionStatisticsInfo()
                            .getWrongCount());
                    questionBaseBean.setQuestionStatisticsInfo(questionStatisticsInfo);

                    QuestionBaseBean.QuestionsAnswerInfo questionsAnswerInfo = new
                            QuestionBaseBean.QuestionsAnswerInfo();
                    questionsAnswerInfo.setQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionsAnswerInfo().getQuestionId());
                    questionsAnswerInfo.setAnswerArray(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray
                                    ());
                    if (!"50".equals(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionTypeId()))
                    if (event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray() != null || event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray().size() != 0) {
                        for (int num = 0; num < event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray().size(); num++) {
                            questionBaseBean.getRightList().add(Helper.stringToAscii(event.getQuestionBaseList().get(i).getQuestionList().get(j).getQuestionsAnswerInfo().getAnswerArray().get(num).toString()));
                        }
                    }
                    questionsAnswerInfo.setFormatContent(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionsAnswerInfo()
                            .getFormatContent());
                    questionsAnswerInfo.setFormatImages(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestionsAnswerInfo()
                            .getFormatImages());
                    questionBaseBean.setQuestionsAnswerInfo(questionsAnswerInfo);

                    QuestionBaseBean.userAnswerInfo userAnswerInfo = new QuestionBaseBean
                            .userAnswerInfo();


                    userAnswerInfo.setAnswerDuration(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getAnswerDuration());
                    userAnswerInfo.setIsState(event.getQuestionBaseList().get(i).getQuestionList
                            ().get(j).getUserAnswerInfo().getIsState());

                    userAnswerInfo.setPaperId(event.getQuestionBaseList().get(i).getQuestionList
                            ().get(j).getUserAnswerInfo().getPaperId());
                    userAnswerInfo.setRealQuestionId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getRealQuestionId());
                    userAnswerInfo.setQuestionNumber(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getQuestionNumber());
                    userAnswerInfo.setQuestionScore(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getQuestionScore());
                    userAnswerInfo.setCateId(event.getQuestionBaseList().get(i)
                            .getQuestionList()
                            .get(j).getUserAnswerInfo().getCateId());
                    userAnswerInfo.setUserAnswer(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getUserAnswer());


                    userAnswerInfo.setUserAnswerId(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getUserAnswerInfo().getUserAnswerId());

                    questionBaseBean.setUserAnswerInfo(userAnswerInfo);


                    ArrayList<questioncontentListBean> questioncontentListBeans = new
                            ArrayList<>();
                    questioncontentListBeans.addAll(event.getQuestionBaseList().get(i)
                            .getQuestionList().get(j).getQuestioncontentList());
                    questionBaseBean.setQuestioncontentList(questioncontentListBeans);

                    if (isHistory) {
                        // 如果是练习历史进来   添加已答数据
                        if (questionBaseBean.getUserAnswerInfo().getUserAnswer().size() == 0) {
                            questionBaseBean.setFinishAnswer(false);
                        } else {
                            questionBaseBean.setFinishAnswer(true);
                            if (questionBaseBean.getQuestionsAnswerInfo().getAnswerArray()
                                    .toString().equals(questionBaseBean.getUserAnswerInfo()
                                            .getUserAnswer().toString())) {
                                questionBaseBean.setChooseResult(true);
                                for (int k = 0; k < questionBaseBean.getQuestioncontentList()
                                        .size(); k++) {
                                    if (questionBaseBean.getQuestioncontentList().get(k)
                                            .getSelectKey().equals(questionBaseBean
                                                    .getUserAnswerInfo().getUserAnswer().get(0))) {
                                        questionBaseBean.setRightAnswer(k + 1);
                                    }
                                }
                            } else {
                                questionBaseBean.setChooseResult(false);
                                for (int k = 0; k < questionBaseBean.getQuestioncontentList()
                                        .size(); k++) {
                                    if (questionBaseBean.getQuestioncontentList().get(k)
                                            .getSelectKey().equals(questionBaseBean
                                                    .getUserAnswerInfo().getUserAnswer().get(0))) {
                                        questionBaseBean.setErrorAnswer(k + 1);
                                    }
                                    if (questionBaseBean.getQuestioncontentList().get(k)
                                            .getSelectKey().equals(questionBaseBean
                                                    .getQuestionsAnswerInfo().getAnswerArray()
                                                    .get(0))) {
                                        questionBaseBean.setRightAnswer(k + 1);
                                    }
                                }
                            }

                        }
                    }
                    ArrayList<QuestionContextListBean> questionContextListBean = new ArrayList<>();
                    questionContextListBean.addAll(event.getQuestionsContextList());
                    questionBaseBean.setQuestionsContextList(questionContextListBean);

                    baseBean.add(questionBaseBean);
                }
            }
            if (isHistory) {
                // 遍历 获得最后答题的position  跳转到此题后面一题
                for (int h = baseBean.size(); h > 0; h--) {
                    if (baseBean.get(h - 1).isFinishAnswer()) {
                        position = h;
                        break;
                    }
                }
            }
            if (Constant.title_tv.equals("1") || Constant.title_tv.equals("2") || Constant.title_tv.equals("7") || Constant.title_tv.equals("8")) {
                if (baseBean.get(position).getQuestionTypeId().equals("10")) { //单选
                    queConect.setText("单项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("20") || baseBean.get(position)
                        .getQuestionTypeId().equals("35")) { //多选
                    queConect.setText("多项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("50")){
                    queConect.setText("主观题");
                }

            } else {
                queConect.setText(baseBean.get(viewPager.getCurrentItem()).getTitle());
            }

            queNum.setText((viewPager.getCurrentItem() + 1) + "/" + baseBean.size());
            viewPager.setCurrentItem(position, false);
        }

        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }


    public static long currentTime = 120 * 60 * 1000;

    public void startTimer() {
        countDownTimer = new DefineTimer(currentTime, 1000) {//2700 45分钟
            @Override
            public void onTick(long l) {
                currentTime = l;
                int allSecond = (int) l / 1000;//秒
                int hour = allSecond / 3600;
                int minute = allSecond / 60 - hour * 60;
                int second = allSecond - (hour * 60 + minute) * 60;
                timer.setText("" + hour + ":" + minute + ":" + second);
            }

            @Override
            public void onFinish() {
                submitAnswer();
            }
        };
        countDownTimer.start();
        System.out.println("时间开始倒计时===" );


    }


    @Override
    protected void onPause() {
        if (isExam) {
            countDownTimer.cancel();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (isExam) {
            countDownTimer.cancel();
        }
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    public static void nextQuestion() {
        if (viewPager.getCurrentItem() <= baseBean.size()) {
            System.out.println("123456题库数组大小===" + baseBean.size());
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.question_back, R.id.question_submit, R.id.settingtv, R.id.remove, R.id.stop,
            R.id.collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.question_back:
                backHandler();
                break;
            case R.id.question_submit:
                EventBus.getDefault().postSticky(baseBean);
                Intent intent = new Intent(QuestionTestActivity.this, AnswerCardActivity.class);
                startActivity(intent);
                break;
            case R.id.settingtv:
                showProductDialog();
                break;
            case R.id.stop:

                //暂停
                if (isstart == false) {
                    countDownTimer.cancel();
                    isstart = true;
                } else {

                }
                final View dialogview = QuestionTestActivity.this.getLayoutInflater().inflate(
                        R.layout.stopclock_xml, null);
                dialog = new Dialog(QuestionTestActivity.this, R.style.dialogStyle1);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();

                dialogview.findViewById(R.id.keep).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                                //继续倒计时，那么就需要减去之前的
                                countDownTimer = new DefineTimer(currentTime, 1000) {//2700 45分钟
                                    @Override
                                    public void onTick(long l) {
                                        currentTime = l;
                                        int allSecond = (int) l / 1000;//秒
                                        int hour = allSecond / 3600;
                                        int minute = allSecond / 60 - hour * 60;
                                        int second = allSecond - (hour * 60 + minute) * 60;
                                        timer.setText("" + hour + ":" + minute + ":" + second);
                                    }

                                    @Override
                                    public void onFinish() {
                                        submitAnswer();
                                    }
                                };
                                countDownTimer.start();
                                System.out.println("时间继续倒计时===" );

                                isstart = false;
                            }
                        });

                dialogview.findViewById(R.id.dialog_ok).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });


                break;
            case R.id.remove:
                delCollect();
                break;
            case R.id.collect:
                if (baseBean.get(pagerPosition).isCollect() == false) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.aff6559));
                    baseBean.get(pagerPosition).setCollect(true);
                    setCollect();
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.a999999));
                    baseBean.get(pagerPosition).setCollect(false);
                    delCollect();
                }
                break;
        }
    }

    private void delCollect() {
        CommentModel.getInstant().delCollect(Constant.adutst, baseBean.get(pagerPosition)
                .getRealQuestionId(), new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                Helper.showToast("取消收藏");
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }

    private void setCollect() {
        CommentModel.getInstant().setCollect(Constant.adutst, baseBean.get(pagerPosition)
                .getRealQuestionId(), new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                Helper.showToast("已收藏");
            }

            @Override
            public void onFailure(String fail) {

            }
        });
    }


    //设置字体大小
    private void showProductDialog() {

        View view = LayoutInflater.from(QuestionTestActivity.this).inflate(R.layout
                .questionseting, null);

        first = (TextView) view.findViewById(R.id.first);
        second = (TextView) view.findViewById(R.id.second);
        three = (TextView) view.findViewById(R.id.three);
        four = (TextView) view.findViewById(R.id.four);
        five = (TextView) view.findViewById(R.id.five);

        int size = MySharedPreferences.getInstance(QuestionTestActivity.this).getTextSize();
        switch (size) {
            case 1:
                textSelect(first);
                break;
            case 2:
                textSelect(second);
                break;
            case 3:
                textSelect(three);
                break;
            case 4:
                textSelect(four);
                break;
            case 5:
                textSelect(five);
                break;
        }
        // 创建PopupWindow对象，指定宽度和高度
        PopupWindow window = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);

        // 设置可以获取焦点
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        // 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
        // 更新popupwindow的状态
        window.update();
        // 以下拉的方式显示，并且可以设置显示的位置
//        window.showAsDropDown(tvProduct, 0, 20);
//        window.showAtLocation(mainBar, Gravity.NO_GRAVITY, 0, Helper.dip2px(this,50));
        int[] location = new int[2];
        mainBar.getLocationOnScreen(location);
        //在控件上方显示
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = view.getMeasuredWidth();
        int popupHeight = view.getMeasuredHeight();
        window.showAtLocation(mainBar, Gravity.NO_GRAVITY, (location[0] + mainBar.getWidth() / 2)
                - popupWidth / 2, location[1] - popupHeight);

        view.findViewById(R.id.first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 1));
                MySharedPreferences.getInstance(QuestionTestActivity.this).setTextSize(1);
                textSelect(first);
            }
        });

        view.findViewById(R.id.second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 2));
                MySharedPreferences.getInstance(QuestionTestActivity.this).setTextSize(2);
                textSelect(second);
            }
        });


        view.findViewById(R.id.three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 3));
                MySharedPreferences.getInstance(QuestionTestActivity.this).setTextSize(3);
                textSelect(three);
            }
        });

        view.findViewById(R.id.four).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 4));
                MySharedPreferences.getInstance(QuestionTestActivity.this).setTextSize(4);
                textSelect(four);
            }
        });

        view.findViewById(R.id.five).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 5));
                MySharedPreferences.getInstance(QuestionTestActivity.this).setTextSize(5);
                textSelect(five);
            }
        });

    }

    private void textSelect(TextView view) {
        first.setSelected(false);
        second.setSelected(false);
        three.setSelected(false);
        four.setSelected(false);
        five.setSelected(false);
        view.setSelected(true);
    }


    class MyPagerChangeListner implements NoPreloadViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            if (Constant.title_tv.equals("1") || Constant.title_tv.equals("2") || Constant
                    .title_tv.equals("7") || Constant.title_tv.equals("8")) {
                if (baseBean.get(position).getQuestionTypeId().equals("10")) { //单选
                    queConect.setText("单项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("20") || baseBean.get(position)
                        .getQuestionTypeId().equals("35")) { //多选
                    queConect.setText("多项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("50")){
                    queConect.setText("主观题");
                }
            }else {
                queConect.setText(baseBean.get(position).getTitle());
            }

            queNum.setText((position + 1) + "/" + baseBean.size());
        }

        @Override
        public void onPageSelected(int position) {
            pagerPosition = position;
            if (Constant.title_tv.equals("1") || Constant.title_tv.equals("2") || Constant
                    .title_tv.equals("7") || Constant.title_tv.equals("8")) {
                if (baseBean.get(position).getQuestionTypeId().equals("10")) { //单选
                    queConect.setText("单项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("20") || baseBean.get(position)
                        .getQuestionTypeId().equals("35")) { //多选
                    queConect.setText("多项选择题");
                }
                if (baseBean.get(position).getQuestionTypeId().equals("50")){
                    queConect.setText("主观题");
                }
            }else {
                queConect.setText(baseBean.get(position).getTitle());
            }
            queNum.setText((position + 1) + "/" + baseBean.size());
            if (baseBean.get(position).isCollect() == true) {
                Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                        .getMinimumHeight());

                collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                collect.setTextColor(getResources().getColor(R.color.aff6559));
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                        .getMinimumHeight());

                collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                collect.setTextColor(getResources().getColor(R.color.a999999));
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            EventBus.getDefault().postSticky(new EvenBaseBean(baseBean, 1));
            return QuestionsFragment.newInstance(position, isAnalysis, isAnalysisOpen);
        }

        @Override
        public int getCount() {
            if (baseBean == null || baseBean.size() == 0) {
                return 0;
            } else {
                return baseBean.size();
            }
        }
    }


    static int rightCount;
    static int errorCount;

    public static void upDataRightAndError() {
        rightCount = 0;
        errorCount = 0;
        for (QuestionBaseBean result : baseBean) {
            if (result.isFinishAnswer()) {
                if (result.isChooseResult()) {
                    rightCount++;
                } else {
                    errorCount++;
                }
            }
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backHandler();
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    public void backHandler() {
        int finishAnswer = 0;
        int rightAnswer = 0;
        for (QuestionBaseBean r : baseBean) {
            if (r.isChooseResult())
                rightAnswer++;
            if (r.isFinishAnswer())
                finishAnswer++;
        }

        if (finishAnswer == 0) {//如果一题都没做那么直接退出
            finish();
            return;

        }

        //还剩多少题没做
        int nofinishanswer = baseBean.size() - finishAnswer;
        if(nofinishanswer==0){

            AlertDialog dialog = new AlertDialog.Builder(this).setTitle("温馨提示").setMessage("已完成练习,确定要交卷并保存本次练习?").setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
//                        submitAnswer();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {


                    JSONObject dataobj = new JSONObject();
                    final JSONArray idCradArray = new JSONArray();

                    int k = baseBean.size();
                    try {

                        for (int j = 0; j < k; j++) {

                            JSONObject stoneObject = new JSONObject();
                            //已经答题的才保存练习
                            if (baseBean.get(j).isFinishAnswer()) {
                                stoneObject.put("PaperId", baseBean.get(j).getPaperId());
                                stoneObject.put("QuestionId", baseBean.get(j).getQuestionId());
                                if (baseBean.get(j).isChooseResult() == true) {
                                    stoneObject.put("QuestionState", "1");// 答题对与错  1 对 2 错
                                } else {
                                    stoneObject.put("QuestionState", "2");// 答题对与错  1 对 2 错
                                }


                                if (baseBean.get(j).isFinishAnswer()) { //已经作答


                                    stoneObject.put("AnswerDuration", String.valueOf(baseBean.get(j)
                                            .getQuestiontime()));//答题时间
                                    System.out.println("答题时间===" + baseBean.get(j).getQuestiontime()
                                            + "==第几题" + j);

                                    if (baseBean.get(j).isChooseResult()) {//判断选择的结果是否正确

                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getRightList().size(); r++) {
                                                Array.put(r, Helper.asciiToString(baseBean.get(j).getRightList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getRightAnswer()));
                                        }

                                        stoneObject.put("UserAnswer", Array);//数组

                                    } else {
                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getResultList().size(); r++) {
                                                Array.put(r, Helper.asciiToString(baseBean.get(j).getResultList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getErrorAnswer()));
                                        }
                                        stoneObject.put("UserAnswer", Array);//数组
                                        System.out.println("答案是答错的答案===" + baseBean.get(j)
                                                .getErrorAnswer() + "==第几题" + j);
                                    }
                                } else {
                                    //没有作答 赋值时间都为0
                                    stoneObject.put("AnswerDuration", "0");//答题时间

                                }


                                stoneObject.put("QuestionScore", baseBean.get(j)
                                        .getQuestionScore());
                                idCradArray.put(stoneObject);
                            }
                        }

                        float score = 0;
                        for (QuestionBaseBean r : baseBean) {
                            if (r.isChooseResult()) {
                                score += Float.valueOf(r.getQuestionScore());

                                System.out.println("本题分数====" + r.getQuestionScore());
                            }


                        }
                        System.out.println("总分数====" + score);


                        CommentModel.getInstant().post_paper(baseBean.get(0).getPaperId(), "1",
                                String.valueOf(score),
                                idCradArray.toString(), new CallBack() {
                                    @Override
                                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                                        QuestionTestActivity.this.finish();
                                        if (SatGuideActivity.instance != null) {
                                            SatGuideActivity.instance.finish();
                                        }

                                    }

                                    @Override
                                    public void onFailure(String fail) {

                                        ToastUtils.showToast(QuestionTestActivity.this, "保存试卷失败,请重新提交");

                                    }
                                });

                        System.out.println("----->A----" + idCradArray.toString() + "----->");
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }


                }
            }).create();
            dialog.show();


        }else{


            AlertDialog dialog = new AlertDialog.Builder(this).setTitle("温馨提示").setMessage("还有" +
                    nofinishanswer + "题未做完,确定退出?退出后保存在练习历史中").setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
//                        submitAnswer();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {


                    JSONObject dataobj = new JSONObject();
                    final JSONArray idCradArray = new JSONArray();

                    int k = baseBean.size();
                    try {

                        for (int j = 0; j < k; j++) {

                            JSONObject stoneObject = new JSONObject();
                            //已经答题的才保存练习
                            if (baseBean.get(j).isFinishAnswer()) {
                                stoneObject.put("PaperId", baseBean.get(j).getPaperId());
                                stoneObject.put("QuestionId", baseBean.get(j).getQuestionId());
                                if (baseBean.get(j).isChooseResult() == true) {
                                    stoneObject.put("QuestionState", "1");// 答题对与错  1 对 2 错
                                } else {
                                    stoneObject.put("QuestionState", "2");// 答题对与错  1 对 2 错
                                }


                                if (baseBean.get(j).isFinishAnswer()) { //已经作答


                                    stoneObject.put("AnswerDuration", String.valueOf(baseBean.get(j)
                                            .getQuestiontime()));//答题时间
                                    System.out.println("答题时间===" + baseBean.get(j).getQuestiontime()
                                            + "==第几题" + j);

                                    if (baseBean.get(j).isChooseResult()) {//判断选择的结果是否正确

                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getRightList().size(); r++) {
                                                Array.put(r, Helper.asciiToString(baseBean.get(j).getRightList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getRightAnswer()));
                                        }

                                        stoneObject.put("UserAnswer", Array);//数组

                                    } else {
                                        JSONArray Array = new JSONArray();
                                        if ("10".equals(baseBean.get(j).getQuestionTypeId()) || "35".equals(baseBean.get(j).getQuestionTypeId())) {
                                            for (int r = 0; r < baseBean.get(j).getResultList().size(); r++) {
                                                Array.put(r, Helper.asciiToString(baseBean.get(j).getResultList().get(r)));
                                            }
                                        } else {
                                            Array.put(Helper.asciiToString(baseBean.get(j).getErrorAnswer()));
                                        }
                                        stoneObject.put("UserAnswer", Array);//数组
                                        System.out.println("答案是答错的答案===" + baseBean.get(j)
                                                .getErrorAnswer() + "==第几题" + j);
                                    }
                                } else {
                                    //没有作答 赋值时间都为0
                                    stoneObject.put("AnswerDuration", "0");//答题时间

                                }


                                stoneObject.put("QuestionScore", baseBean.get(j)
                                        .getQuestionScore());
                                idCradArray.put(stoneObject);
                            }
                        }

                        float score = 0;
                        for (QuestionBaseBean r : baseBean) {
                            if (r.isChooseResult()) {
                                score += Float.valueOf(r.getQuestionScore());

                                System.out.println("本题分数====" + r.getQuestionScore());
                            }


                        }
                        System.out.println("总分数====" + score);


                        CommentModel.getInstant().post_paper(baseBean.get(0).getPaperId(), "9",
                                String.valueOf(score),
                                idCradArray.toString(), new CallBack() {
                                    @Override
                                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                                        QuestionTestActivity.this.finish();
                                        if (SatGuideActivity.instance != null) {
                                            SatGuideActivity.instance.finish();
                                        }

                                    }

                                    @Override
                                    public void onFailure(String fail) {

                                        ToastUtils.showToast(QuestionTestActivity.this, "保存试卷失败,请重新提交");

                                    }
                                });

                        System.out.println("----->A----" + idCradArray.toString() + "----->");
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }


                }
            }).create();
            dialog.show();

        }


    }


    //提交答案
    public void submitAnswer() {
        finish();
    }


}
